/*
Input: tmp/voter_id_panel.dta [panel of geocoded voter-addresses and Polling locations]

Output: tmp/panel_wahlen.dta [contains the distance between voters and polling places]

Main task:
    > calculate street distance b/w address and assigned polling location in each election

Note: 
	> To calculate walking distances, module 'osrmtime' is required; to install follow
		the following steps (only for windows):	

		1. osrmtime package downloaded from github (https://github.com/christophrust/osrmtime),
			saved & unzipped in folder: 05_package
		2. Downloaded OSRM basemap for 'Oberbayern' from http://download.geofabrik.de/europe/germany/bayern.html
			and saved in folder: 05_package/osrm_basemaps
		3. to install, execute:
			cd "$project/05_packages/osrmtime_release1.3.3/"
			net describe osrmtime.pkg, from("$project/05_packages/osrmtime_release1.3.3/")
			net install osrmtime.pkg
			net get osrmtime.pkg
			shell osrminstall.cmd
			cd "$project"
		5. prepare basemaps, execute:
			osrmprepare, mapfile("$project/05_packages/osrm_basemaps/oberbayern-latest.osm.pbf") profile(foot) ///
			osrmdir("$project/05_packages/osrmtime_release1.3.3/osrm_win_v5.14") 
			
*/


** PULL: Balanced panel of geocoded voter-addresses and polling locations 
use "$tmp/voter_id_panel.dta", clear

	// KEEP vars used for distance calculations only
	keep voter_id* wl_id lat* lon*

	// KEEP UNIQUE voter and polling location pairs; (osrmtime does not work with "if")
	duplicates drop voter_id wl_id, force

	// Calculate walking distance between voter and polling location
	cd "$project/05_packages/osrmtime_release1.3.3/"
	 osrmtime lat_vote lon_vote lat_wl lon_wl, mapfile("$project/05_packages/osrm_basemap/oberbayern-latest.osrm") ///
		osrmdir("$project/05_packages/osrmtime_release1.3.3/osrm_win_v5.14")
	cd "$project"
	
	// assert no errors
	assert return_code==0
		
	// Rename generated variable
	ren 	distance street_dist
	
	// Convert walking distance to km & label
	replace street_dist=street_dist/1000
	lab var street_dist "walking distance in km"
	
	// keep pair-identifier and generated distances
	keep voter_id wl_id street_dist 

	// merge unique pairs of voter-PP + distances with full voter-address panel
	merge 1:m voter_id wl_id using "$tmp/voter_id_panel.dta", assert(3) nogen 

	// SAVE: balanced address panel with distances
	order voter_id voter_id_str wahl_id wahl sb stadtbez
	isid voter_id wahl_id
	compress
	save "$tmp/panel_wahlen.dta", replace
